<script setup>
import { onMounted, onUnmounted } from 'vue'
import { DEFAULT_CAMERA_POSITION } from '@/utils/config'
import { setHelper, deleteHelper } from '@/utils/map'

const props = defineProps({
  mapId: {
    type: String,
    required: true,
  },
  options: {
    type: Object,
    required: true,
  },
  removeDefaultBasemap: {
    type: Boolean,
    required: false,
    default: false,
  },
})

const emit = defineEmits(['mapLoad', 'mapUnload'])

let _map = undefined

const preRenderEventHandler = () => {
  _map.scene.light.direction = Cesium.Cartesian3.clone(
    _map.scene.camera.directionWC,
    _map.scene.light.direction,
  )
}

onMounted(() => {
  console.log('map-viewer mounted, ', props.options)
  _map = new window.Cesium.Viewer(props.mapId, props.options)

  if (_map) {
    if (props.removeDefaultBasemap) {
      _map.imageryLayers.remove(_map.imageryLayers.get(0))
    }
    _map.camera.flyTo(DEFAULT_CAMERA_POSITION)
    _map.scene.postProcessStages.fxaa.enabled = false

    _map.scene.light = new Cesium.DirectionalLight({
      direction: _map.scene.camera.directionWC,
    })
    _map.scene.preRender.addEventListener(preRenderEventHandler)

    setHelper(props.mapId, _map)
    emit('mapLoad', props.mapId, _map)
  }
})

onUnmounted(() => {
  if (_map) {
    _map.scene.preRender.removeEventListener(preRenderEventHandler)
    emit('mapUnload', props.mapId, _map)
    deleteHelper(props.mapId)
  }
})
</script>

<template>
  <div class="map-viewer" :id="mapId"></div>
</template>

<style scoped lang="scss"></style>
